{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "BRANCH = 'main'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "o_0K1lsW1dj9"
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
    "\n",
    "Instructions for setting up Colab are as follows:\n",
    "1. Open a new Python 3 notebook.\n",
    "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
    "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
    "4. Run this cell to set up dependencies.\n",
    "\"\"\"\n",
    "# If you're using Google Colab and not running locally, run this cell\n",
    "\n",
    "# install NeMo\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "uglDB-pVh__t",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:\n",
    "# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'\n",
    "\n",
    "! pip install ipywidgets\n",
    "! jupyter nbextension enable --py widgetsnbextension\n",
    "\n",
    "# Please restart the kernel after running this cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "dzqD2WDFOIN-"
   },
   "outputs": [],
   "source": [
    "from nemo.utils.exp_manager import exp_manager\n",
    "from nemo.collections import nlp as nemo_nlp\n",
    "\n",
    "import os\n",
    "import wget \n",
    "import torch\n",
    "import pytorch_lightning as pl\n",
    "from omegaconf import OmegaConf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "daYw_Xll2ZR9"
   },
   "source": [
    "# Task Description\n",
    "Automatic Speech Recognition (ASR) systems typically generate text with no punctuation and capitalization of the words. \n",
    "This tutorial explains how to implement a model in NeMo that will predict punctuation and capitalization for each word in a sentence to make ASR output more readable and to boost performance of the named entity recognition, machine translation or text-to-speech models. \n",
    "We'll show how to train a model for this task using a pre-trained BERT model. \n",
    "For every word in our training dataset we’re going to predict:\n",
    "\n",
    "- punctuation mark that should follow the word and\n",
    "- whether the word should be capitalized"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZnuziSwJ1yEB"
   },
   "source": [
    "# Dataset\n",
    "This model can work with any dataset as long as it follows the format specified below. \n",
    "The training and evaluation data is divided into *2 files: text.txt and labels.txt*. \n",
    "Each line of the **text.txt** file contains text sequences, where words are separated with spaces: [WORD] [SPACE] [WORD] [SPACE] [WORD], for example:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TXFORGBv2Jqu"
   },
   "source": [
    "\n",
    "\n",
    "```\n",
    "when is the next flight to new york\n",
    "the next flight is ...\n",
    "...\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Y7ci55rM2QH8"
   },
   "source": [
    "The **labels.txt** file contains corresponding labels for each word in text.txt, the labels are separated with spaces. Each label in labels.txt file consists of 2 symbols:\n",
    "\n",
    "- the first symbol of the label indicates what punctuation mark should follow the word (where O means no punctuation needed);\n",
    "- the second symbol determines if a word needs to be capitalized or not (where U indicates that the word should be upper cased, and O - no capitalization needed.)\n",
    "\n",
    "In this tutorial, we are considering only commas, periods, and question marks the rest punctuation marks were removed. To use more punctuation marks, update the dataset to include desired labels, no changes to the model needed. \n",
    "\n",
    "Each line of the **labels.txt** should follow the format: \n",
    "[LABEL] [SPACE] [LABEL] [SPACE] [LABEL] (for labels.txt). \n",
    "For example, labels for the above text.txt file should be:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "-94C1-864EW1"
   },
   "source": [
    "\n",
    "\n",
    "```\n",
    "OU OO OO OO OO OO OU ?U\n",
    "OU OO OO OO ...\n",
    "...\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "VsEmwIPO4L4V"
   },
   "source": [
    "The complete list of all possible labels for this task used in this tutorial is: `OO, ,O, .O, ?O, OU, ,U, .U, ?U.`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "SL58EWkd2ZVb"
   },
   "source": [
    "## Download and preprocess the data¶"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "THi6s1Qx2G1k"
   },
   "source": [
    "In this notebook we are going to use a subset of English examples from the [Tatoeba collection of sentences](https://tatoeba.org/eng) this script will download and preprocess the Tatoeba data [NeMo/examples/nlp/token_classification/get_tatoeba_data.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/data/get_tatoeba_data.py). Note, for further experiments with the model, set NUM_SAMPLES=-1 and consider including other datasets to improve model performance. \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "n8HZrDmr12_-"
   },
   "outputs": [],
   "source": [
    "DATA_DIR = PATH TO A DIRECTORY WHERE DATA FROM THIS TUTORIAL IS STORED\n",
    "WORK_DIR = PATH TO A DIRECTORY WHERE SCRIPTS FOR THIS TUTORIAL ARE SAVED\n",
    "MODEL_CONFIG = \"punctuation_capitalization_config.yaml\"\n",
    "\n",
    "# model parameters\n",
    "TOKENS_IN_BATCH = 1024\n",
    "MAX_SEQ_LENGTH = 64\n",
    "LEARNING_RATE = 0.00002\n",
    "NUM_SAMPLES = 10000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "UOeeeCGqI-9c"
   },
   "outputs": [],
   "source": [
    "## download get_tatoeba_data.py script to download and preprocess the Tatoeba data\n",
    "os.makedirs(WORK_DIR, exist_ok=True)\n",
    "if not os.path.exists(WORK_DIR + '/get_tatoeba_data.py'):\n",
    "    print('Downloading get_tatoeba_data.py...')\n",
    "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/data/get_tatoeba_data.py', WORK_DIR)\n",
    "else:\n",
    "    print ('get_tatoeba_data.py is already exists')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "H0ulD2TL13DR"
   },
   "outputs": [],
   "source": [
    "# download and preprocess the data\n",
    "# --clean_dir flag deletes raw Tataoeba data, remove the flag to avoid multiple data downloads if you want to experiment with the dataset size\n",
    "! python $WORK_DIR/get_tatoeba_data.py --data_dir $DATA_DIR --num_sample $NUM_SAMPLES --clean_dir"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "pctMm2vsPlPT"
   },
   "source": [
    "after execution of the above cell, your data folder will contain the following 4 files needed for training (raw Tatoeba data could be present if `--clean_dir` was not used):\n",
    "- labels_dev.txt\n",
    "- labels_train.txt\n",
    "- text_dev.txt\n",
    "- text_train.txt\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "KKwxXXezPvXF"
   },
   "outputs": [],
   "source": [
    "! ls -l $DATA_DIR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "6UDPgadLN6SG"
   },
   "outputs": [],
   "source": [
    "# let's take a look at the data \n",
    "print('Text:')\n",
    "! head -n 5 $DATA_DIR/text_train.txt\n",
    "\n",
    "print('\\nLabels:')\n",
    "! head -n 5 $DATA_DIR/labels_train.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you see, `get_tatoeba_data.py` script provides not only downloads Tatoeba but also creates labels. If you wish to preprocess your own data, use [examples/nlp/token_classification/data/prepare_data_for_punctuation_capitalization.py](https://github.com/NVIDIA/NeMo/blob/main/examples/nlp/token_classification/data/prepare_data_for_punctuation_capitalization.py) script:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cwd = os.getcwd()\n",
    "NEMO_ROOT = \"~/NeMo\"\n",
    "!python $NEMO_ROOT/examples/nlp/token_classification/data/prepare_data_for_punctuation_capitalization.py \\\n",
    "    --source_file $DATA_DIR/text_train.txt \\\n",
    "    --output_dir $DATA_DIR/my_train_preprocessed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls $DATA_DIR/my_train_preprocessed -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tarred dataset\n",
    "\n",
    "If your dataset is too large to be stored in memory, you can use tarred dataset. A tarred dataset is a collection of tarred files which contain batches ready for passing into a model.\n",
    "\n",
    "All tar files will contain indentical number of batches, so if number of batches in the dataset is not evenly divisible by parameter `--num_batches_per_tar_file` value, then up to `--num_batches_per_tar_file - 1` batches may be lost."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Number of lines in text and labels files\n",
    "!wc -l $DATA_DIR/text_train.txt\n",
    "!wc -l $DATA_DIR/labels_train.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NEMO_ROOT = \"~/NeMo\"\n",
    "!python $NEMO_ROOT/examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py \\\n",
    "    --text $DATA_DIR/text_train.txt \\\n",
    "    --labels $DATA_DIR/labels_train.txt \\\n",
    "    --output_dir $DATA_DIR/train_tarred \\\n",
    "    --num_batches_per_tarfile 5 \\\n",
    "    --tokens_in_batch 1024 \\\n",
    "    --lines_per_dataset_fragment 4000 \\\n",
    "    --tokenizer_name bert-base-uncased \\\n",
    "    --n_jobs 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls $DATA_DIR/train_tarred -l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls $DATA_DIR/train_tarred/*.tar | wc -l  # number of tar files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls $DATA_DIR/train_tarred/ | grep -v '.tar'  # all not tar files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you wish to use tarred dataset, then you need to \n",
    "- pass metadata JSON file in config parameter `model.train_ds.tar_metadata_file`,\n",
    "- set `model.train_ds.use_tarred_dataset=true`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "daludzzL2Jba"
   },
   "source": [
    "# Model Configuration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_whKCxfTMo6Y"
   },
   "source": [
    "In the Punctuation and Capitalization Model, we are jointly training two token-level classifiers on top of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model: \n",
    "- one classifier to predict punctuation and\n",
    "- the other one - capitalization.\n",
    "\n",
    "The model is defined in a config file which declares multiple important sections. They are:\n",
    "- **model**: All arguments that are related to the Model - language model, token classifiers, optimizer and schedulers, dataset and any other related information\n",
    "\n",
    "- **trainer**: Any argument to be passed to PyTorch Lightning\n",
    "\n",
    "See [docs](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/nlp/punctuation_and_capitalization.html#training-punctuation-and-capitalization-model) for full config description."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "T1gA8PsJ13MJ"
   },
   "outputs": [],
   "source": [
    "# download the model's configuration file \n",
    "config_dir = WORK_DIR + '/configs/'\n",
    "os.makedirs(config_dir, exist_ok=True)\n",
    "if not os.path.exists(config_dir + MODEL_CONFIG):\n",
    "    print('Downloading config file...')\n",
    "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG, config_dir)\n",
    "else:\n",
    "    print ('config file is already exists')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "mX3KmWMvSUQw"
   },
   "outputs": [],
   "source": [
    "# this line will print the entire config of the model\n",
    "config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'\n",
    "print(config_path)\n",
    "config = OmegaConf.load(config_path)\n",
    "print(OmegaConf.to_yaml(config))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZCgWzNBkaQLZ"
   },
   "source": [
    "# Setting up Data within the config\n",
    "\n",
    "Among other things, the config file contains dictionaries called `common_dataset_parameters`, `train_ds` and `validation_ds`. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
    "\n",
    "Specify paths directories with train and dev datasets in parameters `train_ds.ds_item` and `validation_ds.ds_item`.\n",
    "\n",
    "I you want to use multiple datasets for evaluation, specify paths to the directory(ies) with evaluation file(s) in the following way:\n",
    "\n",
    "`model.validation_ds.ds_item=[PATH_TO_DEV1,PATH_TO_DEV2]` (Note no space between the paths and square brackets).\n",
    "\n",
    "Also notice that some configs, including `model.train_ds.ds_item`, have `???` in place of values, this values are required to be specified by the user.\n",
    "\n",
    "Let's now add the data directory path to the config."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "LQHCJN-ZaoLp"
   },
   "outputs": [],
   "source": [
    "# in this tutorial train and dev data is located in the same folder\n",
    "config.model.train_ds.ds_item = DATA_DIR\n",
    "config.model.validation_ds.ds_item=DATA_DIR\n",
    "del config.model.test_ds  # We do not have test data, only train and dev"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nB96-3sTc3yk"
   },
   "source": [
    "# Building the PyTorch Lightning Trainer\n",
    "\n",
    "NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem!\n",
    "\n",
    "Let's first instantiate a Trainer object!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "1tG4FzZ4Ui60"
   },
   "outputs": [],
   "source": [
    "print(\"Trainer config - \\n\")\n",
    "print(OmegaConf.to_yaml(config.trainer))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "knF6QeQQdMrH"
   },
   "outputs": [],
   "source": [
    "# lets modify some trainer configs\n",
    "# checks if we have GPU available and uses it\n",
    "cuda = 1 if torch.cuda.is_available() else 0\n",
    "config.trainer.gpus = cuda\n",
    "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
    "\n",
    "# For mixed precision training, use precision=16 and amp_level=O1\n",
    "\n",
    "# Reduces maximum number of epochs to 1 for a quick training\n",
    "config.trainer.max_epochs = 1\n",
    "\n",
    "# Remove distributed training flags\n",
    "config.trainer.accelerator = None\n",
    "\n",
    "trainer = pl.Trainer(**config.trainer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8IlEMdVxdr6p"
   },
   "source": [
    "# Setting up a NeMo Experiment¶\n",
    "\n",
    "NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "8uztqGAmdrYt"
   },
   "outputs": [],
   "source": [
    "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
    "\n",
    "# the exp_dir provides a path to the current experiment for easy access\n",
    "exp_dir = str(exp_dir)\n",
    "exp_dir"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "6FI_nQsJo_11"
   },
   "source": [
    "# Model Training"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8tjLhUvL_o7_"
   },
   "source": [
    "Before initializing the model, we might want to modify some of the model configs. For example, we might want to modify the pretrained BERT model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Xeuc2i7Y_nP5"
   },
   "outputs": [],
   "source": [
    "# complete list of supported BERT-like models\n",
    "print(nemo_nlp.modules.get_pretrained_lm_models_list())\n",
    "\n",
    "PRETRAINED_BERT_MODEL = \"bert-base-uncased\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "RK2xglXyAUOO"
   },
   "outputs": [],
   "source": [
    "# add the specified above model parameters to the config\n",
    "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL\n",
    "config.model.train_ds.tokens_in_batch = TOKENS_IN_BATCH\n",
    "config.model.validation_ds.tokens_in_batch = TOKENS_IN_BATCH\n",
    "config.model.optim.lr = LEARNING_RATE\n",
    "config.model.train_ds.num_samples = NUM_SAMPLES\n",
    "config.model.validation_ds.num_samples = NUM_SAMPLES\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gYKcziSsiAAd"
   },
   "source": [
    "Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders we'll be prepared for training and evaluation.\n",
    "Also, the pretrained BERT model will be downloaded, note it can take up to a few minutes depending on the size of the chosen BERT model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Yk2hJssviAAe",
    "pycharm": {
     "name": "#%%\n"
    },
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# initialize the model\n",
    "# during this stage, the dataset and data loaders we'll be prepared for training and evaluation\n",
    "model = nemo_nlp.models.PunctuationCapitalizationModel(cfg=config.model, trainer=trainer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kQ592Tx4pzyB"
   },
   "source": [
    "## Monitoring training progress\n",
    "Optionally, you can create a Tensorboard visualization to monitor training progress."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "mTJr16_pp0aS"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "  from google import colab\n",
    "  COLAB_ENV = True\n",
    "except (ImportError, ModuleNotFoundError):\n",
    "  COLAB_ENV = False\n",
    "\n",
    "# Load the TensorBoard notebook extension\n",
    "if COLAB_ENV:\n",
    "  %load_ext tensorboard\n",
    "  %tensorboard --logdir {exp_dir}\n",
    "else:\n",
    "  print(\"To use tensorboard, please use this notebook in a Google Colab environment.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "hUvnSpyjp0Dh"
   },
   "outputs": [],
   "source": [
    "# start the training\n",
    "trainer.fit(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training using tarred dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = OmegaConf.load(config_path)\n",
    "config.model.train_ds.ds_item = f'{DATA_DIR}/train_tarred'\n",
    "config.model.train_ds.use_tarred_dataset = True\n",
    "# Only metadata file name is required if `use_tarred_dataset=true`.\n",
    "config.model.train_ds.tar_metadata_file = 'metadata.punctuation_capitalization.tokens1024.max_seq_length512.bert-base-uncased.json'\n",
    "config.model.validation_ds.ds_item = DATA_DIR\n",
    "del config.model.test_ds  # We do not have test data, only train and dev\n",
    "\n",
    "# Trainer\n",
    "cuda = 1 if torch.cuda.is_available() else 0\n",
    "config.trainer.gpus = cuda\n",
    "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
    "config.trainer.max_epochs = 1\n",
    "config.trainer.accelerator = None\n",
    "\n",
    "# Exp manager\n",
    "config.exp_manager.explicit_log_dir = 'tarred_experiment'\n",
    "\n",
    "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL\n",
    "config.model.validation_ds.tokens_in_batch = TOKENS_IN_BATCH\n",
    "config.model.optim.lr = LEARNING_RATE\n",
    "config.model.validation_ds.num_samples = NUM_SAMPLES"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer = pl.Trainer(**config.trainer)\n",
    "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
    "model = nemo_nlp.models.PunctuationCapitalizationModel(cfg=config.model, trainer=trainer)\n",
    "trainer.fit(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "VPdzJVAgSFaJ"
   },
   "source": [
    "# Inference\n",
    "\n",
    "To see how the model performs, let’s run inference on a few examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "DQhsamclRtxJ"
   },
   "outputs": [],
   "source": [
    "# define the list of queiries for inference\n",
    "queries = [\n",
    "        'we bought four shirts and one mug from the nvidia gear store in santa clara',\n",
    "        'what can i do for you today',\n",
    "        'how are you',\n",
    "        'how is the weather in',\n",
    "    ]\n",
    "inference_results = model.add_punctuation_capitalization(queries)\n",
    "print()\n",
    "\n",
    "for query, result in zip(queries, inference_results):\n",
    "    print(f'Query   : {query}')\n",
    "    print(f'Combined: {result.strip()}\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Inference for large amounts of text can be performed by a script [examples/nlp/token_classification/punctuate_capitalize_infer.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/punctuate_capitalize_infer.py)\n",
    "\n",
    "```\n",
    "python punctuate_capitalize_infer.py \\\n",
    "    --input_manifest <PATH_TO_INPUT_MANIFEST> \\\n",
    "    --output_manifest <PATH_TO_OUTPUT_MANIFEST> \\\n",
    "    --pretrained_name punctuation_en_bert \\\n",
    "    --max_seq_length 64 \\\n",
    "    --margin 16 \\\n",
    "    --step 8\n",
    "```\n",
    "\n",
    "`<PATH_TO_INPUT_MANIFEST>` is a path to NeMo [ASR manifest](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/asr/datasets.html) which contains text in which you need to restore punctuation and capitalization. If manifest contains `'pred_text'` key, then `'pred_text'` elements will be processed. Otherwise, punctuation and capitalization will be restored in `'text'` elements.\n",
    "\n",
    "`<PATH_TO_OUTPUT_MANIFEST>` is a path to NeMo ASR manifest into which result will be saved. The text with restored\n",
    "punctuation and capitalization is saved into `'pred_text'` elements if `'pred_text'` key is present in\n",
    "input manifest. Otherwise result will be saved into `'text'` elements.\n",
    "\n",
    "Alternatively you can pass text for restoring punctuation and capitalization as plain text. See help for parameters `--input_text` and `--output_text` of the script\n",
    "[punctuate_capitalize_infer.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/punctuate_capitalize_infer.py).\n",
    "\n",
    "The script `examples/nlp/token_classification/punctuate_capitalize_infer.py` can restore punctuation and capitalization in a text of arbitrary length. Long sequences are split into segments\n",
    "`--max_seq_length - 2` tokens each. Each segment starts and ends with `[CLS]` and `[SEP]`\n",
    "tokens correspondingly. Every segment is offset to the previous one by `--step` tokens. For example, if\n",
    "every character is a token, `--max_seq_length=5`, `--step=2`, then text `\"hello\"` will be split into\n",
    "segments `[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]`.\n",
    "\n",
    "If segments overlap, then predicted probabilities for a token present in several segments are multiplied before selecting the best candidate.\n",
    "\n",
    "Splitting leads to pour performance of a model near edges of segments. Use parameter `--margin` to discard `--margin`\n",
    "probabilities predicted for `--margin` tokens near segment edges. For example, if every character is a token, `--max_seq_length=5`, `--step=1`, `--margin=1`, then text `\"hello\"` will be split into segments `[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'e', 'l', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]`. Before calculating actual predictions, probabilities for tokens marked by asterisk are removed: `[['[CLS]', 'h', 'e', 'l'*, '[SEP]'*], ['[CLS]'*, 'e'*, 'l', 'l'*, '[SEP]'*], ['[CLS]'*, 'l'*, 'l', 'o', '[SEP]']]`.\n",
    "\n",
    "You may use parameters `max_seq_length`, `step`, and `margin` in `add_punctuation_capitalization` method.\n",
    "\n",
    "The text in the following example is from IWSLT 2019 test dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inference_results = model.add_punctuation_capitalization(\n",
    "    [\n",
    "        \"each of these songs represents a scene a movement in some cases a sonic revolution that completely altered the \"\n",
    "        \"course of popular music they're all also calling cards almost for those cities songs totally linked with their \"\n",
    "        \"city's identity and might be why you probably consider them to be music cities now the magical mythical thing \"\n",
    "        \"the thing we kind of all love about stories like these is that those cities weren't doing anything in particular \"\n",
    "        \"to make those moments happen there's no formula for capturing lightning in a bottle a formula didn't give us \"\n",
    "        \"grunge music or introduce tupock to dr dray and there's definitely no blueprint for how to open your record \"\n",
    "        \"business in a south memphis neighborhood that turns out is home to booker t jones william bell and albert king \"\n",
    "        \"so this is just something that happens and right when the stars perfectly align great music just happens and \"\n",
    "        \"in the meantime new york and nashville can churn out the hits that come through our radios define our \"\n",
    "        \"generations and soundtrack our weddings and our funerals and everything in between i don't know about you but \"\n",
    "        \"the very idea of that is just deadly boring to me there are musicians all around you making powerful important \"\n",
    "        \"music and thanks to the internet and it's limitless possibilities for creators to create music and fans to \"\n",
    "        \"discover that music those zyite guy songs don't have to be handed down to us from some conference room full of \"\n",
    "        \"songwriters in a corporate high rise but also and more importantly we can't decide that it's just something that \"\n",
    "        \"happens because music is about so much more than hits those big iconic moments that change everything it's more \"\n",
    "        \"than just entertainment for so many of us music is truly a way to navigate life a means of self expression sure \"\n",
    "        \"but it also helps us find ourrselfel worse and figure out who we are it connects us with other people as almost \"\n",
    "        \"nothing else can across language barriers across social and cultural and economic divides music makes us smarter \"\n",
    "        \"and healthier and happier music is necessary what if you lived in a city that believed that that said we're not \"\n",
    "        \"waiting for that hit song to define us we're a music city because music is necessary by seeing music as \"\n",
    "        \"necessary a city can build two things 1st an ecosystem to support the development of professional musicians \"\n",
    "        \"and music business and 2nd a receptive and engaged audience to sustain them and those are the two critical \"\n",
    "        \"elements of a music city a city whose leaders recognize the importance of music for our development as \"\n",
    "        \"individuals our connection as a community and our viability as a vibrant place to live see smart cities music \"\n",
    "        \"cities know that thriving night lifef a creative class culture is what attracts young talented people to cities \"\n",
    "        \"it's what brings that lightning and no we can't predict the next egg that will hatch but we can create a city \"\n",
    "        \"that acts like an incubator to do that 1st we got to know what we've got that means identifying and quantifying \"\n",
    "        \"our assets we need to know them backward and forward from who and what and where they are to what their impact \"\n",
    "        \"is on the economy let's count our recording studios and our record labels our historic landmarks and our \"\n",
    "        \"hardcore punk clubs we should count monthly free jazz nights and weekly folk jams music schools artist \"\n",
    "        \"development instrument shops every lay than every luther music museums open once a open year round and music \"\n",
    "        \"festivals open just one weekend year now ideally through this process we'll create an actual asset map \"\n",
    "        \"dropping a pin for each one allowing us to see exactly what we've got and where organic momentum is already \"\n",
    "        \"happening because it's not enough to paint in broad strokes here when it comes to specific support for music \"\n",
    "        \"locally and a broad understanding of a music brand nationally you've got to have the receipts next we'll need \"\n",
    "        \"to identify our challenges now it's important to knowe that for the most part this won't be just the opposite \"\n",
    "        \"of step one we won't gain a whole lot by simply thinking about what's missing from our map instead we need to \"\n",
    "        \"approach this more holistically there are lots of music venues on our map awesome but are they struggling do \"\n",
    "        \"we have a venue ladder which just means can an artist starting out at a coffee house open mike see a clear path \"\n",
    "        \"for how they'll grow from that 25 seat room to a hundred seat room and so on or are we expecting them to go from \"\n",
    "        \"a coffee house to a colossum maybe our challenges lie in city infrastructure public transportation affordable \"\n",
    "        \"housing maybe like in london where the number of music venues went from 400 in 2010 to 100 in 2015 we need to \"\n",
    "        \"think about protections against gentrification the mayor of london in december of last year actually added \"\n",
    "        \"something called the agent of change principle to the city's comprehensive plan the name says it all if a real \"\n",
    "        \"estate developer wants to build condos next to an existing music venue the developer is the agent of change they \"\n",
    "        \"have to take the necessary steps for noise mitigation next and this is a very big one we need leadership and we \"\n",
    "        \"need a strategy now we know there's a lot of magic in this mix a lot of right people right place right time and \"\n",
    "        \"that will never stop being an important element of the way music is made the way some of the best most enduring \"\n",
    "        \"music is made but there cannot be a leadership vacuum in 2018 surriving music cities don't often happen and \"\n",
    "        \"don't have to happen accidentally we need elected officials who recognize the power of music and elevate the \"\n",
    "        \"voices of creatives and they're ready to put a strategy in place in music cities from berlin to paris to bogata \"\n",
    "        \"music advisory councils ensure that musicians have a seat at the table they're volunteer councils and they work \"\n",
    "        \"directly with a designated advocate inside of city hall or even the chamber of commerce the strongest strategies \"\n",
    "        \"will build music community supports like this one inward while also exporting music outward they go hand in hand \"\n",
    "        \"when we look inward we create that place that musicians want to live and when we look outward we build \"\n",
    "        \"opportunities for them to advance their career while also driving attention back to our city and leveraging music \"\n",
    "        \"as a talent attraction tool and here's something else that will help with that we've got to figure out who we are \"\n",
    "        \"now when i say austin you probably think live music capital and why because in 1991 leadership in austin saw \"\n",
    "        \"something percolating with an existing asset and they chose to own it by recognizing that momentum naming it and \"\n",
    "        \"claiming it they inevitably caused more live music venues to open existing spaces to add live music to their \"\n",
    "        \"repertoire and they created a swell of civic buy in around the idea which meant that it wasn't just a slogan in \"\n",
    "        \"some tourism pamphlet was something that locals really started to believe and take pride in now generally \"\n",
    "        \"speaking what austin created is just an assets based narrative and when we think back to step one we know that \"\n",
    "        \"every city will not tick every box many cities won't have recording studios like memphis or a songwriter and \"\n",
    "        \"publishing scene like nashville and that's not a deal breaker we simply have to find the momentum happening in \"\n",
    "        \"our city what are our unique assets in comparison to no other place so if all of that sounds like something \"\n",
    "        \"you'd like to happen where you live here are three things you can do to move the needle 1st you can use your \"\n",
    "        \"feet your ears and your dollars show up be that receptive and engaged audience that is so necessary for a music \"\n",
    "        \"city to thrive pay a cover charge buy a record discover new music and please take your friends two you can use \"\n",
    "        \"your voice buy in to the assets based narrative talk about and celebrate what your city has and three you can \"\n",
    "        \"use your vote seek out leadership that doesn't just pay lip service to your city's music but recognizes its \"\n",
    "        \"power and is prepared to put a strategy in place to elevate it grow it and build collaboration no there really \"\n",
    "        \"is no telling what city could be defined by a certain scene or a certain song in the next decade but as much \"\n",
    "        \"as we absolutely cannot predict that what we absolutely can predict is what happens when we treat music as \"\n",
    "        \"necessary and we work to build a music city and that is a place where i want to live thank you\"\n",
    "    ],\n",
    "    max_seq_length=128,\n",
    "    step=8,\n",
    "    margin=16,\n",
    "    batch_size=32,\n",
    ")\n",
    "print(inference_results[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ref1qSonGNhP"
   },
   "source": [
    "## Training Script\n",
    "\n",
    "If you have NeMo installed locally, you can also train the model with [nlp/token_classification/punctuation_capitalization_train_evaluate.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/punctuation_capitalization_train_evaluate.py).\n",
    "\n",
    "To run training script, use:\n",
    "\n",
    "`python punctuation_capitalization_train_evaluate.py model.train_ds.ds_item=PATH_TO_TRAIN_DATA_DIR`\n",
    "\n",
    "Set NUM_SAMPLES=-1 and consider including other datasets to improve the performance of the model.\n",
    "\n",
    "# Finetuning model with your data\n",
    "\n",
    "When we were training the model from scratch, the datasets were prepared for training during the model initialization. When we are using a pretrained Punctuation and Capitalization model, before training, we need to setup training and evaluation data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "4X1BahRlkaNf"
   },
   "outputs": [],
   "source": [
    "# let's reload our pretrained model\n",
    "pretrained_model = nemo_nlp.models.PunctuationCapitalizationModel.from_pretrained('punctuation_en_distilbert')\n",
    "\n",
    "# setup train and validation Pytorch DataLoaders\n",
    "pretrained_model.update_config_after_restoring_from_checkpoint(\n",
    "    train_ds={\n",
    "        'ds_item': DATA_DIR,\n",
    "        'text_file': 'text_train.txt',\n",
    "        'labels_file': 'labels_train.txt',\n",
    "        'tokens_in_batch': 1024,\n",
    "    },\n",
    "    validation_ds={\n",
    "        'ds_item': DATA_DIR,\n",
    "        'text_file': 'text_dev.txt',\n",
    "        'labels_file': 'labels_dev.txt',\n",
    "        'tokens_in_batch': 1024,\n",
    "    },\n",
    ")\n",
    "pretrained_model.setup_training_data()\n",
    "pretrained_model.setup_validation_data()\n",
    "\n",
    "# and now we can create a PyTorch Lightning trainer and call `fit` again\n",
    "# for this tutorial we are setting fast_dev_run to True, and the trainer will run 1 training batch and 1 validation batch\n",
    "# for actual model training, disable the flag\n",
    "fast_dev_run = True\n",
    "trainer = pl.Trainer(gpus=1, fast_dev_run=fast_dev_run)\n",
    "trainer.fit(pretrained_model)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [
    "daYw_Xll2ZR9"
   ],
   "name": "Punctuation_and_Capitalization.ipynb",
   "private_outputs": true,
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "metadata": {
     "collapsed": false
    },
    "source": []
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
